﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PS3Helpers.UserControls;
using System.IO;
using PS3Helpers.Helpers;

namespace PS3Helpers
{
    public partial class P3PEditor : UserControl
    {
        private PS3PackageFile _packageFile;
        private bool _lockChangedEvent = false;
        Dictionary<string, int> _fileTypeImages = new Dictionary<string, int>();

        public P3PEditor()
        {
            InitializeComponent();

            comboBoxDataType.Items.Clear();
            comboBoxDataType.Items.Add(new ComboBoxItem("DG - Disc Game", PS3Category.DiscGame));
            comboBoxDataType.Items.Add(new ComboBoxItem("HG - Harddisk Game", PS3Category.HardDiskGame));
            comboBoxDataType.Items.Add(new ComboBoxItem("GD - Game Data", PS3Category.GameData));
            comboBoxDataType.Items.Add(new ComboBoxItem("DP - Disc Package", PS3Category.DiscPackage));
            comboBoxDataType.Items.Add(new ComboBoxItem("DM - Disc Movie", PS3Category.DiscMovie));
            comboBoxDataType.Items.Add(new ComboBoxItem("IP - Install Package", PS3Category.InstallPackage));
            comboBoxDataType.Items.Add(new ComboBoxItem("SD - Game Save Data", PS3Category.GameSaveData));


            checkedListBoxVideoResolution.Items.Clear();
            checkedListBoxVideoResolution.Items.Add(new ComboBoxItem("1080", PS3VideoResolution.vr1080));
            checkedListBoxVideoResolution.Items.Add(new ComboBoxItem("720", PS3VideoResolution.vr720));
            checkedListBoxVideoResolution.Items.Add(new ComboBoxItem("576 (16:9)", PS3VideoResolution.vr576_16x9));
            checkedListBoxVideoResolution.Items.Add(new ComboBoxItem("576", PS3VideoResolution.vr576));
            checkedListBoxVideoResolution.Items.Add(new ComboBoxItem("480 (16:9)", PS3VideoResolution.vr480_16x9));
            checkedListBoxVideoResolution.Items.Add(new ComboBoxItem("480", PS3VideoResolution.vr480));

            checkedListBoxAudioFormat.Items.Clear();
            checkedListBoxAudioFormat.Items.Add(new ComboBoxItem("7.1 LPCM", PS3AudioFormat.LPCM7_1));
            checkedListBoxAudioFormat.Items.Add(new ComboBoxItem("5.1 LPCM", PS3AudioFormat.LPCM5_1));
            checkedListBoxAudioFormat.Items.Add(new ComboBoxItem("2 LPCM", PS3AudioFormat.LPCM2));
            checkedListBoxAudioFormat.Items.Add(new ComboBoxItem("DTS Digital Surround", PS3AudioFormat.DTS));
            checkedListBoxAudioFormat.Items.Add(new ComboBoxItem("Dolby Digital", PS3AudioFormat.DolbyDigital));


            panelLogoPictureBackground.Width = (panelLogoPictureBackground.Height * 320 / 176);

            HookChangeEvents(this.Controls);

            contentIdEditor.ContentIdChanged += ControlChangedEvent;
        }

        private void HookChangeEvents(ControlCollection controls)
        {
            foreach (Control childcontrol in controls)
            {
                System.Windows.Forms.TextBox textbox = childcontrol as System.Windows.Forms.TextBox;
                if (textbox != null)
                {
                    textbox.TextChanged += ControlChangedEvent;
                }

                System.Windows.Forms.CheckBox checkbox = childcontrol as System.Windows.Forms.CheckBox;
                if (checkbox != null)
                {
                    checkbox.CheckedChanged += ControlChangedEvent;
                }

                System.Windows.Forms.RadioButton radiobutton = childcontrol as System.Windows.Forms.RadioButton;
                if (radiobutton != null)
                {
                    radiobutton.CheckedChanged += ControlChangedEvent;
                }

                System.Windows.Forms.ComboBox combobox = childcontrol as System.Windows.Forms.ComboBox;
                if (combobox != null)
                {
                    combobox.SelectedIndexChanged += ControlChangedEvent;
                }

                HookChangeEvents(childcontrol.Controls);
            }

        }

        private void ControlChangedEvent(object sender, EventArgs e)
        {
            NotifyContentChanged();
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Browsable(false)]
        public PS3PackageFile PackageFile
        {
            get
            {
                UpdatePackageFile();
                return _packageFile;
            }
            set
            {
                _packageFile = new PS3PackageFile(value);

                _lockChangedEvent = true;
                try
                {
                    ShowPackageFile();
                }
                finally
                {
                    _lockChangedEvent = false;
                }
            }
        }

        public delegate void ContentChangedHandler(P3PEditor sender);
        public event ContentChangedHandler ContentChanged;

        internal void NotifyContentChanged()
        {
            if (_lockChangedEvent)
                return;

            ContentChangedHandler handler = ContentChanged;

            if (handler != null)
            {
                handler(this);
            }
        }

        #region Show Package File

        private void ShowPackageFile()
        {
            textBoxTitle.Text = _packageFile.Title;
            contentIdEditor.Text = _packageFile.ContentId;
            comboBoxPs3SystemVersion.Text = _packageFile.Ps3SystemVersion;
            textBoxAppVer.Text = _packageFile.AppVer;
            textBoxPkgVer.Text = _packageFile.PkgVer;
            checkBoxAutoIncrement.Checked = _packageFile.AutoIncrement;

            comboBoxParentalLockLevel.SelectedIndex = _packageFile.ParentalLockLevel;
            ComboBoxItem.SetSelectedValue(comboBoxDataType, _packageFile.Category);

            SetCheckedListBoxState(checkedListBoxVideoResolution, _packageFile.VideoResolution);
            SetCheckedListBoxState(checkedListBoxAudioFormat, _packageFile.AudioFormat);

            checkBoxPspRemotePlayAvailable.Checked = ((_packageFile.PspRemotePlayCodec & PSPRemotePlayCodec.Available) != 0);
            radioButtonMpeg4AvcAac.Checked = ((_packageFile.PspRemotePlayCodec & PSPRemotePlayCodec.Mpeg4AvcAac) != 0);
            radioButtonMpeg4SpAtrac.Checked = ((_packageFile.PspRemotePlayCodec & PSPRemotePlayCodec.Mpeg4SpAtrac) != 0);
            checkBoxPspRemotePlayAvailable_CheckedChanged(null, null);


            if (
                !string.IsNullOrEmpty(_packageFile.LogoFilename) &&
                File.Exists(_packageFile.LogoFilename)
               )
            {
                pictureBoxLogo.Load(_packageFile.LogoFilename);
            }
            else
            {
                pictureBoxLogo.Image = null;
            }
            UpdateLogoPicture();

            ListDirectoryStructure();


            // Show title
            StringBuilder sb = new StringBuilder();
            sb.Append(Application.ProductName);

            if (!string.IsNullOrEmpty(_packageFile.Filename))
            {
                sb.Append(" - ");
                sb.Append(Path.GetFileName(_packageFile.Filename));
            }

            this.Text = sb.ToString();
        }

        private void SetCheckedListBoxState(CheckedListBox checkedlistbox, int bitflag)
        {
            for (int idx = 0; idx < checkedlistbox.Items.Count; idx++)
            {
                ComboBoxItem item = (ComboBoxItem)checkedlistbox.Items[idx];

                int intvalue = (int)item.ItemValue;
                bool ischecked = ((bitflag & intvalue) == intvalue);
                checkedlistbox.SetItemChecked(idx, ischecked);
            }
        }

        private TreeNode ListDirectory(TreeNodeCollection targetnodes, VirtualDirectory dir)
        {
            if (dir == null)
                return null;

            TreeNode newnode = targetnodes.Add(dir.Name);
            newnode.Tag = dir;
            newnode.ImageIndex = 0;
            newnode.SelectedImageIndex = 1;

            foreach (VirtualDirectory subdir in dir.Directories)
            {
                ListDirectory(newnode.Nodes, subdir);
            }

            return newnode;
        }

        private void ListDirectoryStructure()
        {
            treeViewFolders.BeginUpdate();
            try
            {
                treeViewFolders.Nodes.Clear();

                TreeNode rootnode = ListDirectory(treeViewFolders.Nodes, _packageFile.RootDir);

                treeViewFolders.SelectedNode = rootnode;
            }
            finally
            {
                treeViewFolders.ExpandAll();
                treeViewFolders.EndUpdate();
            }
        }

        private int GetFileTypeImageIndex(VirtualFile file)
        {
            // Special icon set for locked/PS3 files.
            if (file.Locked)
                return 0;

            // string extension = Path.GetExtension(file.SourceFilename);

            int idx = -1;
            if (_fileTypeImages.TryGetValue(file.SourceFilename, out idx))
            {
                return idx;
            }


            Icon icon = WindowsFileIconHelper.GetIconForFile(file.SourceFilename, false);
            imageListFiles.Images.Add(icon);
            idx = imageListFiles.Images.Count - 1;
            _fileTypeImages.Add(file.SourceFilename, idx);

            return idx;
        }

        private void ListFilesInFolder(TreeNode foldernode)
        {
            listViewFiles.BeginUpdate();
            try
            {
                listViewFiles.Items.Clear();

                VirtualDirectory dir = (VirtualDirectory)foldernode.Tag;

                foreach (VirtualFile file in dir.Files)
                {
                    int imgidx = GetFileTypeImageIndex(file);
                    ListViewItem fileitem = new ListViewItem(file.Name, imgidx);
                    fileitem.Tag = file;
                    fileitem.SubItems.Add(file.SourceFilename);

                    listViewFiles.Items.Add(fileitem);
                }
            }
            finally
            {
                listViewFiles.EndUpdate();
            }
        }

        #endregion Show Package File

        #region Generate Package File

        private void UpdatePackageFile()
        {
            _packageFile.Title = textBoxTitle.Text;
            _packageFile.ContentId = contentIdEditor.Text;
            _packageFile.Ps3SystemVersion = comboBoxPs3SystemVersion.Text;
            _packageFile.AppVer = textBoxAppVer.Text;
            _packageFile.PkgVer = textBoxPkgVer.Text;
            _packageFile.AutoIncrement = checkBoxAutoIncrement.Checked;
            _packageFile.LogoFilename = pictureBoxLogo.ImageLocation;


            _packageFile.ParentalLockLevel = comboBoxParentalLockLevel.SelectedIndex;
            _packageFile.Category = (PS3Category)ComboBoxItem.GetSelectedValue(comboBoxDataType);


            _packageFile.VideoResolution = GetCheckedListBoxBitFlag(checkedListBoxVideoResolution);
            _packageFile.AudioFormat = GetCheckedListBoxBitFlag(checkedListBoxAudioFormat);


            _packageFile.PspRemotePlayCodec = 0;
            if (checkBoxPspRemotePlayAvailable.Checked) _packageFile.PspRemotePlayCodec = _packageFile.PspRemotePlayCodec | PSPRemotePlayCodec.Available;
            if (radioButtonMpeg4AvcAac.Checked) _packageFile.PspRemotePlayCodec = _packageFile.PspRemotePlayCodec | PSPRemotePlayCodec.Mpeg4AvcAac;
            if (radioButtonMpeg4SpAtrac.Checked) _packageFile.PspRemotePlayCodec = _packageFile.PspRemotePlayCodec | PSPRemotePlayCodec.Mpeg4SpAtrac;
        }

        private int GetCheckedListBoxBitFlag(CheckedListBox checkedlistbox)
        {
            int result = 0;

            for (int idx = 0; idx < checkedlistbox.Items.Count; idx++)
            {
                if (!checkedlistbox.GetItemChecked(idx))
                    continue;

                ComboBoxItem item = (ComboBoxItem)checkedlistbox.Items[idx];

                int intvalue = (int)item.ItemValue;
                result = result | intvalue;
            }

            return result;
        }

        #endregion Generate Package File

        private void UpdateLogoPicture()
        {
            labelLogoPictureOverlay.Dock = DockStyle.Fill;
            labelLogoPictureOverlay.Visible = (pictureBoxLogo.Image == null);
            pictureBoxLogo.Visible = (pictureBoxLogo.Image != null);

            NotifyContentChanged();
        }

        private void pictureBoxLogo_Click(object sender, EventArgs e)
        {
            MouseEventArgs me = (e as MouseEventArgs);
            if (me != null && me.Button != System.Windows.Forms.MouseButtons.Left)
                return;

            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "PNG Files|*.png";

            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                pictureBoxLogo.Load(ofd.FileName);
                UpdateLogoPicture();

                if (pictureBoxLogo.Image.Width != 320 || pictureBoxLogo.Image.Height != 176)
                {
                    MessageBox.Show("Recommended resolution for logo picture is 320x176.", "Resolution", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private void treeViewFolders_AfterSelect(object sender, TreeViewEventArgs e)
        {
            ListFilesInFolder(e.Node);
        }

        private void checkBoxPspRemotePlayAvailable_CheckedChanged(object sender, EventArgs e)
        {
            radioButtonMpeg4AvcAac.Enabled = checkBoxPspRemotePlayAvailable.Checked;
            radioButtonMpeg4SpAtrac.Enabled = checkBoxPspRemotePlayAvailable.Checked;
        }

        private void removeLogoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            pictureBoxLogo.Image = null;
            UpdateLogoPicture();
        }

        #region Drag & Drop support

        private void listViewFiles_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy; // Ok.
            }
            else
            {
                e.Effect = DragDropEffects.None; // Unknown data. Ignore it.
            }
        }

        private void listViewFiles_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

            AddFiles(files);
        }

        private TreeNode _lastDragHoveredNode = null;

        private void treeViewFolders_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy; // Ok.
                treeViewFolders.DragOver += treeViewFolders_DragOver;
            }
            else
            {
                e.Effect = DragDropEffects.None; // Unknown data. Ignore it.
            }
        }

        private void treeViewFolders_DragOver(object sender, DragEventArgs e)
        {
            if (e.AllowedEffect == DragDropEffects.None)
                return;

            Point pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));
            TreeNode DestinationNode = ((TreeView)sender).GetNodeAt(pt);

            FocusNode(_lastDragHoveredNode, false);
            _lastDragHoveredNode = DestinationNode;
            FocusNode(_lastDragHoveredNode, true);
        }

        private void treeViewFolders_DragDrop(object sender, DragEventArgs e)
        {
            CleanupTreeViewDrag();


            Point pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));
            TreeNode DestinationNode = ((TreeView)sender).GetNodeAt(pt);

            VirtualDirectory dir = (VirtualDirectory)DestinationNode.Tag;

            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
            foreach (string filename in files)
            {
                VirtualFile vf = new VirtualFile(filename);
                dir.Files.Add(vf);
            }

            // treeViewFolders.SelectedNode = DestinationNode; // Should we change the selected node to the destination node?
            ListFilesInFolder(treeViewFolders.SelectedNode);

            NotifyContentChanged();
        }

        private void treeViewFolders_DragLeave(object sender, EventArgs e)
        {
            CleanupTreeViewDrag();
        }

        private void CleanupTreeViewDrag()
        {
            FocusNode(_lastDragHoveredNode, false);
            _lastDragHoveredNode = null;

            treeViewFolders.DragOver -= treeViewFolders_DragOver;
        }

        private void FocusNode(TreeNode node, bool showhovered)
        {
            if (node == null)
                return;

            if (showhovered)
            {
                node.BackColor = SystemColors.Highlight;
                node.ForeColor = SystemColors.HighlightText;
            }
            else
            {
                node.BackColor = treeViewFolders.BackColor;
                node.ForeColor = treeViewFolders.ForeColor;
            }
        }

        #endregion Drag & Drop support

        #region Folder Management

        private void treeViewFolders_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button != System.Windows.Forms.MouseButtons.Right)
                return;

            TreeNode selnode = treeViewFolders.GetNodeAt(e.Location);

            if (selnode != null)
            {
                selnode.BackColor = SystemColors.Highlight;
                selnode.ForeColor = SystemColors.HighlightText;
            }

            // addFolderToolStripMenuItem.Enabled = (selnode != null);
            renameFolderToolStripMenuItem.Enabled = (selnode != null) && (selnode.Parent != null);
            deleteFolderToolStripMenuItem.Enabled = (selnode != null) && (selnode.Parent != null);

            contextMenuStripFolders.Tag = selnode;
            contextMenuStripFolders.Show(treeViewFolders.PointToScreen(e.Location));
        }

        private void contextMenuStripFolders_Closed(object sender, ToolStripDropDownClosedEventArgs e)
        {
            TreeNode selnode = contextMenuStripFolders.Tag as TreeNode;
            if (selnode != null)
            {
                selnode.BackColor = Color.Empty;
                selnode.ForeColor = Color.Empty;
            }
        }

        private void addFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode selnode = contextMenuStripFolders.Tag as TreeNode;
            VirtualDirectory parentdir = (selnode == null) ? null : selnode.Tag as VirtualDirectory;

            string foldername = "";
            if (InputBox.Show("Add Folder", "New Folder Name", ref foldername, AddFolderCallback) == DialogResult.OK)
            {
                VirtualDirectory newdir = new VirtualDirectory(foldername);
                parentdir.Directories.Add(newdir);

                ListDirectoryStructure();
            }
        }

        private void renameFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode foldernode = contextMenuStripFolders.Tag as TreeNode;
            RenameFolder(foldernode);
        }

        private void RenameFolder(TreeNode foldernode)
        {
            if (foldernode == null)
                return;

            VirtualDirectory currentdir = foldernode.Tag as VirtualDirectory;

            string foldername = currentdir.Name;
            if (InputBox.Show("Rename Folder '" + currentdir.Name + "'", "New Folder Name", ref foldername, RenameFolderCallback) == DialogResult.OK)
            {
                foldername = foldername.Trim();
                currentdir.Name = foldername;
                foldernode.Text = foldername;
            }
        }

        private string AddFolderCallback(InputBox sender, string currenttext)
        {
            return AddRenameFolderCallback(sender, currenttext, false);
        }

        private string RenameFolderCallback(InputBox sender, string currenttext)
        {
            return AddRenameFolderCallback(sender, currenttext, true);
        }

        private string AddRenameFolderCallback(InputBox sender, string currenttext, bool isrename)
        {
            currenttext = currenttext.Trim();

            if (string.IsNullOrEmpty(currenttext))
                return "Please fill in a valid folder name!";


            TreeNode selnode = contextMenuStripFolders.Tag as TreeNode;
            VirtualDirectory curdir = (VirtualDirectory)selnode.Tag;

            VirtualDirectory parentdir = (selnode == null) ? null : selnode.Tag as VirtualDirectory;
            if (parentdir == null) // Woot?
                return "An error occured. Please close the current window!";

            
            VirtualDirectoryCollection dirs = isrename ? parentdir.Parent.Directories : parentdir.Directories;
            foreach (VirtualDirectory subdir in dirs)
            {
                if (subdir == curdir)
                    continue;

                if (subdir.Name.Equals(currenttext, StringComparison.CurrentCultureIgnoreCase))
                {
                    return "Directory already exist!";
                }
            }

            return null;
        }

        private void deleteFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode selnode = contextMenuStripFolders.Tag as TreeNode;
            DeleteDir(selnode);
        }

        private void treeViewFolders_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Delete:
                    {
                        DeleteDir(treeViewFolders.SelectedNode);
                        break;
                    }
                case Keys.F2:
                    {
                        RenameFolder(treeViewFolders.SelectedNode);
                        break;
                    }
            }
        }

        private void DeleteDir(TreeNode dirnode)
        {
            VirtualDirectory dir = dirnode.Tag as VirtualDirectory;

            if (MessageBox.Show(string.Format("Delete directory '{0}'?", dir.Name), "Delete Directory", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                dir.Parent.Directories.Remove(dir);
                ListDirectoryStructure();
            }
        }

        #endregion Folder Management

        #region File Management


        private void listViewFiles_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button != System.Windows.Forms.MouseButtons.Right)
                return;

            // Check if the selection has any locked files
            bool selectionhaslockedfiles = false;
            foreach (ListViewItem fileitem in listViewFiles.SelectedItems)
            {
                VirtualFile vf = (VirtualFile)fileitem.Tag;
                if (vf.Locked)
                {
                    selectionhaslockedfiles = true;
                    break;
                }
            }

            // addFilesToolStripMenuItem.Enabled = true;
            renameFileToolStripMenuItem.Enabled = (listViewFiles.SelectedItems.Count == 1) && (!selectionhaslockedfiles);
            deleteFilesToolStripMenuItem.Enabled = (listViewFiles.SelectedItems.Count > 0) && (!selectionhaslockedfiles);

            contextMenuStripFiles.Show(listViewFiles.PointToScreen(e.Location));
        }

        private void addFilesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Multiselect = true;
                ofd.CheckFileExists = true;
                ofd.Filter = "All Files|*.*";

                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    AddFiles(ofd.FileNames);
                }
            }
        }

        private void renameFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RenameSelectedFile();
        }

        private void RenameSelectedFile()
        {
            if (listViewFiles.SelectedItems.Count != 1)
                return;

            // Check if the selection has any locked files
            foreach (ListViewItem fileitem in listViewFiles.SelectedItems)
            {
                VirtualFile vf = (VirtualFile)fileitem.Tag;
                if (vf.Locked)
                {
                    return;
                }
            }


            ListViewItem selitem = listViewFiles.SelectedItems[0];
            VirtualFile currentfile = (selitem == null) ? null : selitem.Tag as VirtualFile;

            string filename = currentfile.Name;
            if (InputBox.Show("Rename File '" + currentfile.Name + "'", "New File Name", ref filename, RenameFileCallback) == DialogResult.OK)
            {
                filename = filename.Trim();
                currentfile.Name = filename;
                selitem.Text = filename;
            }
        }

        private string RenameFileCallback(InputBox sender, string currenttext)
        {
            currenttext = currenttext.Trim();

            if (string.IsNullOrEmpty(currenttext))
                return "Please fill in a valid file name!";

            
            foreach (ListViewItem fileitem in listViewFiles.Items)
            {
                if (listViewFiles.SelectedItems.Contains(fileitem))
                    continue;

                VirtualFile vf = (VirtualFile)fileitem.Tag;
                if (vf.Name.Equals(currenttext, StringComparison.CurrentCultureIgnoreCase))
                {
                    return "File already exist!";
                }
            }

            return null;
        }

        private void deleteFilesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeleteSelectedFiles();
        }

        private void listViewFiles_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Delete:
                    {
                        DeleteSelectedFiles();
                        break;
                    }
                case Keys.F2:
                    {
                        RenameSelectedFile();
                        break;
                    }
            }
        }

        private void DeleteSelectedFiles()
        {
            if (listViewFiles.SelectedItems.Count == 0)
                return;

            if (MessageBox.Show("Remove the selected items from the current folder?", "Remove", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                foreach (ListViewItem curitem in listViewFiles.SelectedItems)
                {
                    VirtualFile vf = (VirtualFile)curitem.Tag;
                    vf._ownerDirectory.Files.Remove(vf);
                }

                ListFilesInFolder(treeViewFolders.SelectedNode);
            }
        }

        private void AddFiles(string[] files)
        {
            VirtualDirectory dir = (VirtualDirectory)treeViewFolders.SelectedNode.Tag;

            foreach (string filename in files)
            {
                VirtualFile vf = new VirtualFile(filename);
                dir.Files.Add(vf);
            }

            ListFilesInFolder(treeViewFolders.SelectedNode);
            NotifyContentChanged();
        }

        #endregion File Management
    }
}
